// ffmpeg about video / audio
// Installed ffmpeg on system.

import { spawn } from 'child_process'
import fs from 'fs'
import path from 'path'
import {mkdir} from './fileutil.js'

//grab image from video at time
export const getImage = (videoFilePath, jpgFilePath, time = 1, wh) => {
  return new Promise((r, j) => {
    let cmdarr = ['-y','-i', videoFilePath, '-y', '-f', 'image2', '-ss', time, '-t', '10'];
    if (wh) {
      cmdarr.push('-s')
      cmdarr.push(wh);
    }
    cmdarr.push(jpgFilePath);
    let ls = spawn('ffmpeg', cmdarr, {});
    ls.on('close', code => {
      r();
    });
    ls.on('error', err => {
      j(err);
    })
  })
};
/**
 * create m3u8 from video
 */
export const getM3u8 = (videoFilePath,m3u8Folder,hlsTime=5)=>{
  mkdir(m3u8Folder);
  let filePath = path.join(m3u8Folder, 'index.m3u8');
  //开始转换
  return new Promise((r, j) => {
    let ls = spawn('ffmpeg', ['-y','-i', videoFilePath, '-c:v', 'libx264', '-c:a', 'aac', '-strict','-2','-hls_list_size','0','-hls_time',hlsTime,'-f','hls',filePath], {});
    ls.on('close', () => {
      r();
    });
    ls.on('error', err => {
      j(err);
    })
  })
}
/**
 * split video 
 * @param {String} videoFilePath 
 * @param {Number} start second
 * @param {Number} time second
 * @param {String} storeFilePath 
 */
export const getVideo = (videoFilePath,start=0,time=10,storeFilePath) => {
  //开始转换
  mkdir(path.dirname(storeFilePath));
  return new Promise((r, j) => {
    let ls = spawn('ffmpeg', ['-y','-i', videoFilePath, '-ss', start, '-t', time,storeFilePath], {});
    ls.on('close', () => {
      r();
    });
    ls.on('error', err => {
      j(err);
    })
  })
}
/**
 * 
 * @param {String} collapseFile file.txt - file 1.ts\nfile 2.ts
 * @param {*} storeFilePath 
 * @returns 
 */
export const collapse = (collapseFilePath, storeFilePath) => {
  collapseFilePath = collapseFilePath.replace(/\\/g, '/');
  storeFilePath = storeFilePath.replace(/\\/g, '/');
  return new Promise((r, j) => {
    let ls = spawn('ffmpeg', ['-y','-f', 'concat', '-safe', 0, '-i', collapseFilePath, storeFilePath], {});
    ls.on('close', () => { r() });
    ls.on('error', err => { j(err) });
  });
}